package com.ruoyi.quartz.utils;

import com.ruoyi.quartz.domain.SysJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledFuture;

@Service
public class TaskService {
    private Logger log = LoggerFactory.getLogger(TaskService.class);
    private final TaskScheduler taskScheduler; // 可直接注入TaskScheduler的Bean
    private Map<Long, ScheduledFuture> taskMap = new ConcurrentHashMap<>();

    //构造器注入，免@Autowired
    public TaskService(TaskScheduler taskScheduler) {
        this.taskScheduler = taskScheduler;
    }

    public void schedule(SysJob job){
        log.info("注册定时任务 {} - {}", job.getCronExpression(), job.getInvokeTarget());
        RunnableTask task = new RunnableTask(job);
        CronTrigger cronTrigger = new CronTrigger(job.getCronExpression());
        //api接受实际执行的任务，和定时启动的cron表达式
        taskMap.put(job.getJobId(),taskScheduler.schedule(task,cronTrigger));
    }

    public void cancel(Long jobId){
        log.info("取消定时任务 {}", jobId);
        ScheduledFuture s = taskMap.remove(jobId);
        if(s != null){
            s.cancel(true);
        }
    }
}
